<?php
class erpapi_shop_matrix_taobao_request_finance extends erpapi_shop_request_finance
{
    /**
    * 实时获取[支付宝]交易记录
    * @access public
    * @param String $start_time 开始时间
    * @param String $end_time 结束时间
    * @param Int $page 当前请求页码
    * @param Int $limit 每页请求数量
    */
    public function trade_search($start_time,$end_time,$page=1,$limit=100,$alipay_order_no='',$merchant_order_no=''){
        $rs = array('rsp'=>'fail','msg'=>'','msg_code'=>'','msg_id'=>'','data'=>'');
        if ( empty($start_time) || empty($end_time)){
            $rs['msg'] = 'start_time,end_time不能为空';
            return $rs;
        }

        $params = array(
            // 'order_status' => 'ACC_FINISHED',#TODO:不获取交易数据，即在线支付的,交易数据交由任务号接口获取，如果不指定,则只能在程序段进行过滤
            'start_time' => $start_time,
            'end_time' => $end_time,
            'page_no' => $page,
            'page_size' => $limit,
        );
        if($alipay_order_no)$params['alipay_order_no']=$alipay_order_no;
        if($merchant_order_no)$params['merchant_order_no']=$merchant_order_no;
        $callback = array();//实时接口不需要设置
        
        $title = sprintf('获取[支付宝]交易记录%s~%s',$start_time,$end_time);

        $result = $this->__caller->call(SHOP_USER_TRADE_SEARCH,$params,$callback,$title,10,$this->__channelObj->channel['name']);

        #错误代码：w01001 为时间跨度不能超过7天
        $rs['rsp'] = $result['rsp'] == 'success' ? 'succ' : $result['rsp'];
        $rs['msg'] = $result['err_msg'];
        $rs['msg_code'] = $result['err_code'];
        $rs['msg_id'] = $result['msg_id'];

        if (isset($result['data']) && $result['data']){
            $data = json_decode(iconv('gbk','utf-8',$result['data']),true);
            $rs['data'] = array(
                'total_results' => $data['total_results'],
                'total_pages'   => $data['total_pages'],
                'total_records' => $data['trade_records'] ? $data['trade_records']['trade_record'] : array(),//交易记录列表
            );
        }else{
            $rs['data'] = array();
        }
        return $rs;
    }

    #获取退款凭证
    public function getRefundMessage($refundinfo){
        if (!$refundinfo['refund_bn']) return false;
        $params = array(
            'refund_id'=>  $refundinfo['refund_bn'],
        );
        $title = '获取店铺退款凭证';
        $result = $this->__caller->call(SHOP_GET_REFUND_MESSAGE, $params, array(), $title, 10, $refundinfo['refund_bn']);
        if($result['data']) {
            $result['data'] = json_decode($result['data'], true);
        }
        return $result;
    }

    public function addRefundMemo($refundinfo){
        $orderModel = app::get('ome')->model('orders');
        $order = $orderModel->dump($refundinfo['order_id'], 'order_bn');
        $params = array();
        $params['refund_id'] = $refundinfo['refund_apply_bn'];
        $params['content'] = $refundinfo['content'];
        $params['image'] = $refundinfo['imagebinary'];
        $callback = array(
            'class' => get_class($this),
            'method' => 'callback',
        );
        $title = '店铺('.$this->__channelObj->channel['name'].')添加[退款留言]'.'(订单号:'.$order['order_bn'].'退款单号:'.$refundinfo['refund_apply_bn'].')';;
        $rs = $this->__caller->call(SHOP_ADD_REFUND_MESSAGE,$params,$callback,$title,10,$order['order_bn']);
        return $rs;
    }

    #单拉获取退款单详情
    public function getRefundDetail($refund_id ,$refund_phase,$tid) {
        $params = array();
        $params['refund_id'] = $refund_id;
        $params['refund_phase'] = $refund_phase;
        $params['tid'] = $tid;
        $title = "店铺(".$this->__channelObj->channel['name'].")获取前端店铺".$tid."的退款单详情";
        $rsp = $this->__caller->call(SHOP_GET_TRADE_REFUND_RPC,$params,array(),$title,10,$tid);
        if($rsp['data']) {
            $rsp['data'] = json_decode($rsp['data'], true);
        }
        return $rsp;
    }

    protected function _updateRefundApplyStatusApi($status){
        $api_method = '';
        switch($status){
            case '3':
                $api_method = SHOP_REFUSE_REFUND;
                break;
        }
        return $api_method;
    }

    protected function _updateRefundApplyStatusParam($refund,$status){
        $oRefund_taobao = app::get('ome')->model('refund_apply_taobao');
        $refundData = $oRefund_taobao->getList('oid',array('refund_apply_bn'=>$refund['refund_apply_bn']), 0, 1);
        $refundRow = $refundData[0];
        $params = array(
            'refund_id'  =>$refund['refund_apply_bn'],
            'refuse_proof'=>$refund['refuse_proof'],
            'refuse_message'=>$refund['refuse_message'],
        );
        if ($status == '3') {#退款单拒绝
            $params['oid'] = $refundRow['oid'];
        }
        return $params;
    }

    /**
     * 财务科目
     *
     * @return void
     * @author
     **/
    public function bill_account_get($account_id = array())
    {
        $rs = array('rsp'=>'fail','msg'=>'','msg_code'=>'','msg_id'=>'','data'=>'');

        $denytime = array(
            0 => array(mktime(9,30,0,date('m'),date('d'),date('Y')),mktime(11,0,0,date('m'),date('d'),date('Y'))),
            1 => array(mktime(14,0,0,date('m'),date('d'),date('Y')),mktime(17,0,0,date('m'),date('d'),date('Y'))),
            2 => array(mktime(20,0,0,date('m'),date('d'),date('Y')),mktime(22,30,0,date('m'),date('d'),date('Y'))),
            2 => array(mktime(1,0,0,date('m'),date('d'),date('Y')),mktime(3,0,0,date('m'),date('d'),date('Y'))),
        );

        $now = time();
        foreach ($denytime as $value) {
            if ($value[0]<=$now && $now<=$value[1]) {
                $rs['msg'] = 'deny time';
                // return $rs;
            }
        }

        $params = array(
            'fields' => 'account_id,account_code,,account_name,account_type,related_order,gmt_create,gmt_modified,status',
        );

        if ($account_id) $params['aids'] = implode(',', $account_id);

        $title = '店铺[' . $this->__channelObj->channel['name'] . ']获取财务科目';

        // $callback = array(
        //     'class' => get_class($this),
        //     'method' => 'bill_account_get_callback',
        // );

        $return = $this->__caller->call(SHOP_BILL_ACCOUNTS_GET,$params,null,$title,10);

        return $this->bill_account_get_callback($return,null);
    }

    private $outer_account_id = array('3200052031','3200053031','3200013031','3200058031','3200060031','3200059031','3200061031','3200011031','3200063031','3200036031','3200065031','3200066031','3210085031','3200038031','3200062031','3200102041','3200034031','3200050031','3200037031','3200030031','3200021031','3200039031','3122765031','3200084031','3200084031','3200032031','3200027031','3200045031','3200031031');

    public function bill_account_get_callback($response, $callback_params)
    {
        if ($response['rsp'] == 'succ' && $response['data']) {
            $data = @json_decode($response['data'], true);
            $feeTypeModel = app::get('finance')->model('bill_fee_type');
            $feeItemModel = app::get('finance')->model('bill_fee_item');
            foreach ((array) $data['accounts']['top_account_dto'] as $account) {
                // 判断科目类型
                $fee_type = $feeTypeModel->dump(array('outer_account_type' => $account['account_type']));
                if (!$fee_type) continue;

                // 判断科目是否存在
                $fee_item = $feeItemModel->dump(array('fee_item_code' => $account['account_code'], 'channel' => 'tmall'));
                $item = array(
                    'fee_item_id'      => $fee_item ? $fee_item['fee_item_id'] : null,
                    'fee_type_id'      => $fee_type['fee_type_id'],
                    'fee_item'         => $account['account_name'],
                    'inlay'            => 'true',
                    'channel'          => 'tmall',
                    'createtime'       => time(),
                    'fee_item_code'    => $account['account_code'],
                    'outer_account_id' => $account['account_id'],
                    'related_order'    => ($fee_type['fee_type_id'] == '1' || in_array($account['account_id'], $this->outer_account_id)) ? 'true' : 'false',
                );
                $feeItemModel->save($item);
            }
        }

        return $this->callback($response, $callback_params);
    }
}